//
//  YCJSController.m
//  SWWH
//
//  Created by 尚往文化 on 17/2/15.
//  Copyright © 2017年 cy. All rights reserved.
//

#import "YBJSController.h"
#import "UIAlertView+Block.h"
#import "UINavigationController+YB.h"
#import "NSUserDefaults+Extension.h"
#import "UIView+YBLoading.h"

@interface YBJSController ()

@property (strong, nonatomic, readonly) JSContext *context;

@end

@implementation YBJSController

//+ (void)initialize
//{
//    // UserAgent应该包含iPhone字段 不然会导致支付宝H5支付加载不出css
//    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"YBUNITS_iPhone_CLIENT", @"UserAgent", nil];
//    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
//}

- (void)dealloc
{
     YBLog(@"%s", __FUNCTION__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithText:@"\U0000e678" color:[UIColor whiteColor] size:CGSizeMake(22, 22)] style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    
    [self setupUI];
}

- (void)share
{
    //分享的标题
    NSString *textToShare = self.navigationItem.title;
    if (textToShare.length==0) {
        return;
    }
    //分享的图片
    UIImage *imageToShare = [UIImage imageNamed:@"share"];
    //分享的url
    NSURL *urlToShare = [NSURL URLWithString:self.url];
    //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
    NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    //不出现在活动项目
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            YBLog(@"completed");
            //分享 成功
        } else  {
            YBLog(@"cancled");
            //分享 取消
        }
    };
}


- (void)reloadData
{
     [self setupUI];
}

- (void)setupUI
{
     _context = nil;
     [self.webView removeFromSuperview];
     _webView = nil;
     
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, self.view.height-64)];
    self.webView.scrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
        
//    _context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    
//     [self yb_setupContext];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];
}

- (void)yb_setupContext
{
     YBWeakSelf
     //获取版本信息
     self.context[@"YBUnits_IOS_SDK_getVersion"] = (NSString *)^() {
          return [weakSelf yb_getVersion];
     };
    
     //跳转页面
     self.context[@"YBUnits_IOS_SDK_push"] = (id)^(NSString *url) {
          [weakSelf yb_push:url];
     };
     self.context[@"YBUnits_IOS_SDK_quit_push"] = (id)^(NSString *url) {
          [weakSelf yb_quit_push:url];
     };
     self.context[@"YBUnits_IOS_SDK_push_index"] = (id)^(NSString *url, NSInteger index) {
          [weakSelf yb_push_index:url index:index];
     };
     
     //拨打电话号码
     self.context[@"YBUnits_IOS_SDK_callPhoneCode"] = (id)^(NSString *phone) {
          [weakSelf yb_callPhoneCode:phone];
     };
    
    
    NSString *userAgent = [self.context evaluateScript:@"navigator.userAgent"].toString;
    YBLog(@"UserAgent = %@", userAgent);
    
    //设置标题
    NSString *title = [self.context evaluateScript:@"document.title"].toString;
    if (self.navigationItem.title.length==0) {
        self.navigationItem.title = title;
    }
}

- (void)registFuncationWithName:(NSString *)funcName handle:(id)handle
{
    self.context[funcName] = handle;
}

- (JSValue *)runJS:(NSString *)js
{
    return [self.context evaluateScript:js];
}

- (void)setUrl:(NSString *)url
{
    _url = [url copy];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [self.webView loadRequest:request];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    YBLog(@"开始加载......%@", url);
    if (navigationType==UIWebViewNavigationTypeLinkClicked) {
        
        YBJSController *vc = [YBJSController new];
        vc.url = url;
        [self.navigationController pushViewController:vc animated:YES];
        return NO;
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.view stop];
    [self.view loading:CGRectMake(0, 0, kScreenW, kScreenH-64)];
}

- (void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext *)ctx
{
    _context = nil;
    _context = ctx;
    [self yb_setupContext];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.view stop];
    //禁止长按弹出图片的地址等
    [self.context evaluateScript:@"document.body.style.webkitTouchCallout='none';"];
    //禁止长按复制
    [self.context evaluateScript:@"document.documentElement.style.webkitUserSelect='none';"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self.view stop];
    YBLog(@"%@", error.localizedDescription);
}

- (void)yb_callPhoneCode:(NSString *)phone
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIAlertView alertWithTitle:nil message:[NSString stringWithFormat:@"是否拨打电话%@", phone] buttonIndex:^(NSInteger index) {
            if (index == 1) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", phone]]];
            }
        } cancelButtonTitle:@"取消" otherButtonTitles:@"确定"] show];
    });
}

- (void)yb_push:(NSString *)url
{
    YBJSController *jsVC = [[YBJSController alloc] init];
    jsVC.url = url;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController pushViewController:jsVC animated:YES];
    });
}

- (void)yb_quit_push:(NSString *)url
{
    YBJSController *jsVC = [[YBJSController alloc] init];
    jsVC.url = url;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController yb_pushViewController:jsVC animated:YES];
    });
}

//index表示   push之后的控制器 back返回到第几个控制器
- (void)yb_push_index:(NSString *)url index:(NSInteger)index
{
     YBJSController *jsVC = [[YBJSController alloc] init];
     jsVC.url = url;
     dispatch_async(dispatch_get_main_queue(), ^{
          
          NSMutableArray *vcs = [self.navigationController.viewControllers mutableCopy];
          if (vcs.count-index>0) {
               [vcs removeObjectsInRange:NSMakeRange(index, vcs.count-index)];
          }
          [vcs addObject:jsVC];
          [self.navigationController setViewControllers:vcs animated:YES];
     });
}

-  (NSString *)yb_getVersion
{
    return kVersion;
}


@end

